package imageuploader.core;

import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author nir
 * 
 *
 * This class provide a dynamicly event listener registration, like in JavaScript, 
 * You can create and add/remove any event that you want, custom events too.
 */
public class CustomEvent {

    private HashMap<String, ArrayList<CustomEventListener>> listeners;
    
    public CustomEvent(){
        listeners = new HashMap<String, ArrayList<CustomEventListener>>();
    }
    
    /**
     * 
     * @param name  event name 
     * @param listener  the listener class
     */
    public void addEventListener(String name, CustomEventListener listener){
        ArrayList<CustomEventListener> handlers;
        if(listeners.containsKey(name)){
            handlers = listeners.get(name);
            if(handlers!=null) handlers.add(listener);
        }else{
            handlers = new ArrayList<CustomEventListener>();
            handlers.add(listener);
            listeners.put(name, handlers);
        }
    }
    
    /**
     * 
     * @param name  event name 
     * @param listener  the listener class
     */
    public void removeEventListener(String name, CustomEventListener listener){
        ArrayList<CustomEventListener> handlers = listeners.get(name);
        if(handlers!=null && handlers.contains(listener)){
            handlers.remove(listener);
        }
    }
    
    /**
     * 
     * @param name event name to dispatchs
     */
    public void dispatchEvent(String name){
        ArrayList<CustomEventListener> handlers = listeners.get(name);
        if(handlers!=null){
            for(CustomEventListener listener: handlers){
                listener.handle();
            }
        }
    }
    
}
